package com.alog.storage.ui.widget;

import android.app.Activity;
import android.content.Context;
import android.graphics.Bitmap;
import android.graphics.Canvas;
import android.graphics.Rect;
import android.graphics.drawable.BitmapDrawable;
import android.graphics.drawable.Drawable;
import android.support.v4.view.ViewPager;
import android.util.AttributeSet;
import android.view.MotionEvent;
import android.view.View;
import android.view.ViewConfiguration;
import android.view.ViewGroup;
import android.widget.FrameLayout;
import android.widget.HorizontalScrollView;
import android.widget.Scroller;
import com.alog.storage.R;
import java.util.LinkedList;
import java.util.List;

/**
 * 左移退出界面的控件
 */
public class SlideBackLayout extends FrameLayout {
    private View mContentView;
    private final int LEFT_TOUCH_MAX = 100;
    private int mTouchSlop;
    private int mDownX;
    private int mDownY;
    private int mTempX;
    private Scroller mScroller;
    private int mCurViewWidth;
    private boolean mSilding;
    private boolean mFinish;
    private Drawable mShadowDrawable;
    private Activity mActivity;
    private List<ViewPager> mViewPagers = new LinkedList<ViewPager>();
    private List<HorizontalScrollView> mHScrollViews = new LinkedList<HorizontalScrollView>();
    private boolean mTouchMove = true;
    private SlideFinishListener mSlideFinishListener;

    public SlideBackLayout(Context context) {
        super(context);
        init(context);
    }

    public SlideBackLayout(Context context, AttributeSet attrs) {
        this(context, attrs, 0);
    }

    public SlideBackLayout(Context context, AttributeSet attrs, int defStyle) {
        super(context, attrs, defStyle);
        init(context);
    }

    private void init(Context context) {
        mTouchSlop = ViewConfiguration.get(context).getScaledTouchSlop();
        mScroller = new Scroller(context);
        mShadowDrawable = getResources().getDrawable(R.mipmap.shadow_left);
    }

    public void attachToActivity(Activity activity, Bitmap bgBitmap) {
        mActivity = activity;
        ViewGroup rootView = (ViewGroup) activity.getWindow().getDecorView();
        ViewGroup childView = (ViewGroup) rootView.getChildAt(0);
        rootView.removeView(childView);
        addView(childView);
        setContentView(childView);
        rootView.addView(this);
        if (bgBitmap != null) {
            Drawable drawable = new BitmapDrawable(bgBitmap);
            rootView.setBackgroundDrawable(drawable);
        }
    }

    public void setTouchMove(boolean touchMove) {
        mTouchMove = touchMove;
    }

    private void setContentView(View childView) {
        mContentView = (View) childView.getParent();
    }

    @Override
    protected void onLayout(boolean changed, int l, int t, int r, int b) {
        super.onLayout(changed, l, t, r, b);
        if (changed) {
            mCurViewWidth = this.getWidth();
            getAlLViewPager(this);
            getAlLHScrollView(this);
        }
    }

    private void getAlLViewPager(ViewGroup parent) {
        int childCount = parent.getChildCount();
        for (int i = 0; i < childCount; i++) {
            View child = parent.getChildAt(i);
            if (child instanceof ViewPager) {
                mViewPagers.add((ViewPager) child);
            } else if (child instanceof ViewGroup) {
                getAlLViewPager((ViewGroup) child);
            }
        }
    }

    private void getAlLHScrollView(ViewGroup parent) {
        int childCount = parent.getChildCount();
        for (int i = 0; i < childCount; i++) {
            View child = parent.getChildAt(i);
            if (child instanceof HorizontalScrollView) {
                mHScrollViews.add((HorizontalScrollView) child);
            } else if (child instanceof ViewGroup) {
                getAlLHScrollView((ViewGroup) child);
            }
        }
    }

    @Override
    protected void dispatchDraw(Canvas canvas) {
        super.dispatchDraw(canvas);
        if (mShadowDrawable != null && mContentView != null) {
            int left = mContentView.getLeft() - mShadowDrawable.getIntrinsicWidth();
            int right = left + mShadowDrawable.getIntrinsicWidth();
            int top = mContentView.getTop();
            int bottom = mContentView.getBottom();
            mShadowDrawable.setBounds(left, top, right, bottom);
            mShadowDrawable.draw(canvas);
        }
    }

    @Override
    public boolean onInterceptTouchEvent(MotionEvent ev) {
        /*ViewPager viewPager = getTouchViewPager(ev);
        if (viewPager != null && viewPager.getCurrentItem() != 0) {
            return super.onInterceptTouchEvent(ev);
        }
        HorizontalScrollView hScrollView = getTouchHScrollView(ev);
        if (hScrollView != null && hScrollView.getScrollX() != 0) {
            return super.onInterceptTouchEvent(ev);
        }*/
        if (ev.getRawX() > LEFT_TOUCH_MAX) {
            return super.onInterceptTouchEvent(ev);
        }
        switch (ev.getAction()) {
            case MotionEvent.ACTION_DOWN:
                mDownX = mTempX = (int) ev.getRawX();
                mDownY = (int) ev.getRawY();
                break;
            case MotionEvent.ACTION_MOVE:
                int moveX = (int) ev.getRawX();
                if (moveX - mDownX > mTouchSlop && Math.abs((int) ev.getRawY() - mDownY) < mTouchSlop) {
                    return true;
                }
                break;
        }
        return super.onInterceptTouchEvent(ev);
    }

    private ViewPager getTouchViewPager(MotionEvent ev) {
        if (mViewPagers == null || mViewPagers.size() == 0) {
            return null;
        }
        Rect rect = new Rect();
        for (ViewPager v : mViewPagers) {
            v.getHitRect(rect);
            if (rect.contains((int) ev.getX(), rect.bottom - rect.top)) {
                return v;
            }
        }
        return null;
    }

    private HorizontalScrollView getTouchHScrollView(MotionEvent ev) {
        if (mHScrollViews == null || mHScrollViews.size() == 0) {
            return null;
        }
        Rect rect = new Rect();
        for (HorizontalScrollView v : mHScrollViews) {
            v.getHitRect(rect);
            if (rect.contains((int) ev.getX(), rect.bottom - rect.top)) {
                return v;
            }
        }
        return null;
    }

    @Override
    public boolean onTouchEvent(MotionEvent event) {
        switch (event.getAction()) {
            case MotionEvent.ACTION_MOVE:
                if (mTouchMove) {
                    int moveX = (int) event.getRawX();
                    int deltaX = mTempX - moveX;
                    mTempX = moveX;
                    if (moveX - mDownX > mTouchSlop && Math.abs((int) event.getRawY() - mDownY) < mTouchSlop) {
                        mSilding = true;
                    }
                    if (moveX - mDownX >= 0 && mSilding) {
                        mContentView.scrollBy(deltaX, 0);
                    }
                }
                break;
            case MotionEvent.ACTION_UP:
                if (mTouchMove) {
                    mSilding = false;
                    if (mContentView.getScrollX() <= -mCurViewWidth / 2) {
                        mFinish = true;
                        scrollRight();
                    } else {
                        scrollOrigin();
                        mFinish = false;
                    }
                } else {
                    int upX = (int) event.getRawX();
                    if (upX - mDownX > mTouchSlop && Math.abs((int) event.getRawY() - mDownY) < mTouchSlop) {
                        mFinish = true;
                        mActivity.onBackPressed();
                    }
                }
                break;
        }
        return true;
    }

    private void scrollRight() {
        final int delta = (mCurViewWidth + mContentView.getScrollX());
        mScroller.startScroll(mContentView.getScrollX(), 0, -delta + 1, 0, Math.abs(delta));
        postInvalidate();
    }

    private void scrollOrigin() {
        int delta = mContentView.getScrollX();
        mScroller.startScroll(mContentView.getScrollX(), 0, -delta, 0, Math.abs(delta));
        postInvalidate();
    }

    @Override
    public void computeScroll() {
        if (mScroller.computeScrollOffset()) {
            mContentView.scrollTo(mScroller.getCurrX(), mScroller.getCurrY());
            postInvalidate();
            if (mScroller.isFinished() && mFinish) {
                if (mSlideFinishListener != null) {
                    mSlideFinishListener.onFinish();
                }
            }
        }
    }

    public void setSlideFinishListener(SlideFinishListener slideFinishListener) {
        mSlideFinishListener = slideFinishListener;
    }

    public interface SlideFinishListener {
        public void onFinish();
    }

}
